package com.su.common;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 统一异常处理类
 */
@ControllerAdvice(basePackages = "com.su.controller")
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * 账号已存在异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        if (e.getMessage().contains("Duplicate entry")) {
            String[] strings = e.getMessage().split(" ");
            String msg = strings[2];
            msg = msg.replace("'", "");
            return R.error(msg + "已存在");
        }
        return R.error("系统未知异常");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException e){
        return R.error(e.getMessage());
    }
}
